'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  
  //1. 用户注册
  async register() {
        //接收前端注册信息
        let registrationMessage=this.ctx.request.body// 获取用户注册信息JSON对象
        let username = registrationMessage.username;   //用户名
        let mail = registrationMessage.mail;           //邮箱
        let psw=registrationMessage.psw;             //密码

        //判断邮箱是否已被注册
        let verifyUserResult=await this.ctx.service.user.verifyuser(mail);
        if(verifyUserResult){
          //调用邮件发送服务
        await this.ctx.service.user.mailSet(username,mail);
        
        //创建新用户，并存储用户信息
        let userbuilted=await this.ctx.service.user.buildUser(username,psw,mail);
        if(userbuilted){
          this.ctx.body={
            code:200,
            message:"用户创建成功！"
          }
        }else{
          this.ctx.body={
            code:400,
            message:"注册信息存储失败！"
          }
        }
        }else{
          this.ctx.body={
            code:400,
            message:"邮箱已被注册！"
          }
        }
          
  }

  //2. 用户登录
  async login(){
    //接收前端登录信息
    let usermail=this.ctx.request.body.mail;
    let userpsw=this.ctx.request.body.psw;
    
    //调用login函数进行密码校验并根据邮箱生成token
    let token=await this.ctx.service.user.login(usermail,userpsw);
    if (token) {
      this.ctx.body = {
          code: 200,
          message: true,
          token,
      }
  } else {
      this.ctx.body = {
          code: 400,
          message: false,
      }
  }
  }

  //3. 用户详情信息
  async userDetail(){
    let id = this.ctx.cookies.get('userid',{
      maxAge: 10000 * 1000,
      httpOnly: false,
      overwrite: true,
      signed: false,
  }) 
    let detailData=await this.service.user.userDetail(id);
    this.ctx.body=detailData;
  }

  async userDetailId(){
    let id=this.ctx.params.id;
    let detailData=await this.service.user.userDetail(id);
    this.ctx.body=detailData;
  }

  //4.用户信息修改
  async userDetailChange(){
    let id = this.ctx.cookies.get('userid',{
      maxAge: 10000 * 1000,
      httpOnly: false,
      overwrite: true,
      signed: false,
  })
  let changeDetailData=this.ctx.request.body;//其中birth参数一定要传，否则会报错。
  let changeResult=await this.service.user.userDetailChange(id,changeDetailData);
  this.ctx.body=changeResult;
  }

  //5.用户密码修改
  async changePassword(){
    let id = this.ctx.cookies.get('userid',{
      maxAge: 10000 * 1000,
      httpOnly: false,
      overwrite: true,
      signed: false,
  })
    let passwordData=this.ctx.request.body;
    let changeResult=await this.service.user.changePassword(id,passwordData);
    this.ctx.body=changeResult;
  }
}

module.exports = UserController;